package saxion.speelveld.spaceengineer;

import java.util.Calendar;
import java.util.Observable;
import java.util.Observer;

import saxion.speelveld.spaceengineer.buildings.Mines;
import saxion.speelveld.spaceengineer.buildings.ResearchLab;
import saxion.speelveld.spaceengineer.buildings.SpaceCube;
import saxion.speelveld.spaceengineer.buildings.SpaceMarket;
import saxion.speelveld.spaceengineer.buildings.SpaceSchool;
import saxion.speelveld.spaceengineer.controller.AsyncTaskManager;
import saxion.speelveld.spaceengineer.controller.TimedEvents;
import saxion.speelveld.spaceengineer.controller.newGameCreator;
import saxion.speelveld.spaceengineer.database.AchievementDAO;
import saxion.speelveld.spaceengineer.database.BuildingDAO;
import saxion.speelveld.spaceengineer.database.BuildingTypeDAO;
import saxion.speelveld.spaceengineer.database.GameDAO;
import saxion.speelveld.spaceengineer.database.ResourceDAO;
import saxion.speelveld.spaceengineer.database.TileDAO;
import saxion.speelveld.spaceengineer.database.TradeDealsDAO;
import saxion.speelveld.spaceengineer.database.TradePlanetsDAO;
import saxion.speelveld.spaceengineer.model.Achievement;
import saxion.speelveld.spaceengineer.model.Building;
import saxion.speelveld.spaceengineer.model.BuildingTile;
import saxion.speelveld.spaceengineer.model.Difficulties;
import saxion.speelveld.spaceengineer.model.Game;
import saxion.speelveld.spaceengineer.model.Resource;
import saxion.speelveld.spaceengineer.model.ResourceAndPlanetWrapper;
import saxion.speelveld.spaceengineer.model.ResourceType;
import saxion.speelveld.spaceengineer.model.ResourceWrapper;
import saxion.speelveld.spaceengineer.view.GameField;
import saxion.speelveld.spaceengineer.view.ResourceHeader;
import saxion.speelveld.spaceengineer.view.tabs.CurrentBuildings;
import saxion.speelveld.spaceengineer.view.tabs.GameMenu;
import saxion.speelveld.spaceengineer.view.tabs.GameResources;
import saxion.speelveld.spaceengineer.view.tabs.UpgradeScreen;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.Toast;

public class GameScreen extends TabActivity implements Observer
{
	public static final int BUILDING_SCREEN_REQUEST_CODE = 3;

	public static final int TRADING = 4;

	public static final int UPGRADE_SCREEN_REQUEST_CODE = 5;

	public static final int SELL_SCREEN_REQUEST_CODE = 6;

	public static final int ACHIEVEMENT_SCREEN_REQUEST_CODE = 9;

	private GameField gameField;

	private ResourceHeader resourceHeader;

	private GameMenu menu;

	private Game game;

	private TabHost mTabHost;

	private GameDAO gameDatasource;

	private ResourceDAO resourceDatasource;

	private TileDAO tileDatasource;

	private ProgressDialog progdialog;

	private AchievementDAO achievementDatasource;

	private BuildingTypeDAO buildingTypeDatasource;

	private BuildingDAO buildingDatasource;

	private TradeDealsDAO tradeDealsDatasource;

	private TradePlanetsDAO tradePlanetDatasource;

	private long lastUpdateTimeInMillis;

	private static boolean updateAsyncTaskRunning = false;

	private static boolean loadAsyncTaskRunning = false;

	private boolean afterLoadReady = false;

	private boolean stopTimerFromPausing = false;

	public static boolean tabIsSet = false;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
		{
			getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED,
				WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
		}
		setContentView(R.layout.activity_game_screen);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		progdialog = new ProgressDialog(this);
		progdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		progdialog.setIndeterminate(false);
		progdialog.setCancelable(false);

		achievementDatasource = new AchievementDAO(getApplicationContext());
		gameDatasource = new GameDAO(getApplicationContext());
		resourceDatasource = new ResourceDAO(getApplicationContext());
		tileDatasource = new TileDAO(getApplicationContext());
		buildingTypeDatasource = new BuildingTypeDAO(getApplicationContext());
		buildingDatasource = new BuildingDAO(getApplicationContext());
		tradeDealsDatasource = new TradeDealsDAO(getApplicationContext());
		tradePlanetDatasource = new TradePlanetsDAO(getApplicationContext());

		int gameid = getIntent().getExtras().getInt("GameID");
		if (gameid < 0)
		{
			game = createGame();
			progdialog.setMax(110 + game.getResourceArray().length + game.getTradePlantes().length);
			progdialog.setProgress(0);
			progdialog.show();

			new SaveNewGameToDB().execute(this);
		}
		else
		{
			progdialog.setIndeterminate(true);
			progdialog.show();

			Log.i("GameScreen", "start loading in AsyncTask");

			loadAsyncTaskRunning = true;
			new LoadSaveGameFromDB().execute(gameid);
			// game = loadGame(gameid);
		}

		gameField = (GameField) findViewById(R.id.gameField1);
		resourceHeader = (ResourceHeader) findViewById(R.id.resourceHeader1);

		// Tabjes

		mTabHost = getTabHost();

		Drawable homeTabIcon = getResources().getDrawable(R.drawable.ic_tab_options_selected);
		Drawable buildingTabIcon = getResources().getDrawable(R.drawable.ic_tab_home_selected);
		Drawable resourceTabIcon = getResources().getDrawable(R.drawable.ic_tab_resources_selected);

		mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("", homeTabIcon).setContent(R.id.gameMenu));
		mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("", buildingTabIcon)
			.setContent(R.id.currentBuildings));
		mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("", resourceTabIcon)
			.setContent(R.id.gameResources));
		mTabHost.addTab(mTabHost.newTabSpec("tab_test4").setIndicator("Building information")
			.setContent(R.id.upgradeBuilding));

		mTabHost.setCurrentTab(0);
		mTabHost.getTabWidget().getChildAt(3).setVisibility(View.GONE);

		// niet werkende code? :(
		for (int tabs = 0; tabs < mTabHost.getTabWidget().getChildCount(); tabs++)
		{
			View v = mTabHost.getTabWidget().getChildAt(tabs).getTouchables().get(0);
			if (v instanceof ViewGroup)
			{
				ViewGroup vg = ((ViewGroup) v);
				int childCount = vg.getChildCount();
				for (int i = 0; i < childCount; i++)
				{
					View vgv = vg.getChildAt(i);
					if (vgv instanceof ImageView)
					{

					}
					else
					{
						vgv.setVisibility(View.GONE);
						// Log.e("oh yeah", "made it pooof!");
					}
				}
			}
		}

		// TODO: dit in andere functie en aanroepen in/na AsyncTask?
		// Hier word het game model meegegeven aan de tabjes.
		// if (game != null)
		// {
		// afterLoad();
		// }

	}

	public void afterLoad()
	{
		GameMenu gameMenu = (GameMenu) findViewById(R.id.gameMenu);
		gameMenu.setGameModel(game);

		GameResources gameResources = (GameResources) findViewById(R.id.gameResources);
		gameResources.setGameModel(this.game);

		CurrentBuildings currentBuildings = (CurrentBuildings) findViewById(R.id.currentBuildings);
		currentBuildings.setGameModel(game);
		currentBuildings.setTabHost(mTabHost);

		UpgradeScreen upgradeScreen = (UpgradeScreen) findViewById(R.id.upgradeBuilding);
		upgradeScreen.setGameModel(game);

		// eind Tabjes

		game.addObserver(this);
		resourceHeader.setGame(game);
		gameField.SetGame(game);

		Log.w("afterLoad()", "Timer should start right here!");
		TimedEvents.StopTimer();
		// TimedEvents.RestartTimer(game);
		TimedEvents timedEvents = new TimedEvents(game);

		afterLoadReady = true;

	}

	private Game loadGame(int gameID)
	{
		// Maybe kan de eerste boolean op true worden gezet wat betenkent dat je de voortgang moet bijhouden....
		progdialog.show(this, "Loading Game", "Please wait while your game is loading", false, false);
		// loading to be done
		progdialog.dismiss();
		return game;
	}

	private Game createGame()
	{
		Game gametoreturn = null;
		progdialog.setTitle("Creating Game");
		progdialog.setMessage("Please wait while your game is being created");

		int gamedifint = getIntent().getExtras().getInt("Difficultie");
		Difficulties dif;
		switch (gamedifint)
		{
		case 0:
			dif = Difficulties.EASY;
			break;
		case 1:
			dif = Difficulties.NORMAL;
			break;
		case 2:
			dif = Difficulties.HARD;
			break;
		case 3:
			dif = Difficulties.INSANE;
			break;
		default:
			dif = Difficulties.NORMAL;
			break;
		}
		gametoreturn = newGameCreator.GenGame(dif, 100);

		return gametoreturn;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_game_screen, menu);
		return true;
	}

	@Override
	public void update(Observable observable, Object data)
	{
		if (data == null)
		{
			if (game.getResourceAmount(ResourceType.SAND) >= 10)
			{
				achievementDatasource.open();
				Achievement achie = achievementDatasource.getAchievement(6);
				if (achie.isAccomplished() == false)
				{
					showNewAchievementAlert(achie);
				}
			}
			if (game.getResourceAmount(ResourceType.HAPPINESS) >= 60)
			{
				achievementDatasource.open();
				Achievement achie = achievementDatasource.getAchievement(5);
				if (achie.isAccomplished() == false)
				{
					showNewAchievementAlert(achie);
				}
			}
			if (game.getResourceAmount(ResourceType.HAPPINESS) == 100)
			{
				achievementDatasource.open();
				Achievement achie = achievementDatasource.getAchievement(2);
				if (achie.isAccomplished() == false)
				{
					showNewAchievementAlert(achie);
				}
			}
			if (game.getDifficulty().equals("INSANE"))
			{
				if (game.getResourceAmount(ResourceType.HAPPINESS) == 100)
				{
					achievementDatasource.open();
					Achievement achie = achievementDatasource.getAchievement(3);
					if (achie.isAccomplished() == false)
					{
						showNewAchievementAlert(achie);
					}
				}
			}
			achievementDatasource.close();

		}
		else if ((Boolean) data == true)
		{
			achievementDatasource.open();
			Achievement achie = achievementDatasource.getAchievement(1);
			if (achie.isAccomplished() == false)
			{

				for (Building building : game.getBuildings())
				{
					if (building instanceof Mines)
					{
						showNewAchievementAlert(achie);
					}
				}
			}

			achie = achievementDatasource.getAchievement(8);
			if (achie.isAccomplished() == false)
			{
				int spacecubeteller = 0;
				for (Building building : game.getBuildings())
				{
					if (building instanceof SpaceCube)
					{
						spacecubeteller += 1;
						if (spacecubeteller == 10)
						{
							showNewAchievementAlert(achie);
						}
					}
				}
			}

			achie = achievementDatasource.getAchievement(9);
			if (achie.isAccomplished() == false)
			{
				boolean hasResearchLab = false;
				boolean hasSpaceSchool = false;
				for (Building building : game.getBuildings())
				{

					if (building instanceof ResearchLab)
					{
						hasResearchLab = true;
					}
					if (building instanceof SpaceSchool)
					{
						hasSpaceSchool = true;
					}
					if (hasResearchLab == true && hasSpaceSchool == true)
					{
						showNewAchievementAlert(achie);
						break;
					}
				}
			}
			achievementDatasource.close();
		}

		if (updateAsyncTaskRunning == false && afterLoadReady == true
			&& AsyncTaskManager.getAsyncTaskStatus() == Status.FINISHED)
		{
			AsyncTaskManager.setAsyncTask(new SaveCurrentGame().execute(getApplicationContext()));
			lastUpdateTimeInMillis = Calendar.getInstance().getTimeInMillis();
			updateAsyncTaskRunning = true;
		}
		else
		{
			Log.e("SaveCurrentGame", "Not Starting?");
		}

		if (game.getSelectedTile() != null)
		{
			if (tabIsSet == false)
			{
				getTabHost().setCurrentTab(3);
				tabIsSet = true;
			}

		}
		else
		{
			tabIsSet = false;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		String buildingIdFromPackage = "saxion.speelveld.spaceengineer.buildingscreen.buildingid";
		String buildingClassFromPackage = "saxion.speelveld.spaceengineer.buildingscreen.buildingclass";
		if (resultCode == RESULT_OK && requestCode == BUILDING_SCREEN_REQUEST_CODE)
		{
			if (data.hasExtra(buildingIdFromPackage))
			{
				// int buildingId = data.getIntExtra(buildingIdFromPackage, 0);
				// buildingId = 525;
				// Toast.makeText(getApplicationContext(), buildingId + "", Toast.LENGTH_LONG).show();
			}
			if (data.hasExtra(buildingClassFromPackage))
			{
				Building b = (Building) data.getSerializableExtra(buildingClassFromPackage);

				game.setQueuedBuilding(b);
				// Toast.makeText(getBaseContext(), b.getBuildingName(), Toast.LENGTH_LONG).show();
			}
		}
		else if (requestCode == ACHIEVEMENT_SCREEN_REQUEST_CODE)
		{
			stopTimerFromPausing = false;
		}
		else if (resultCode == RESULT_OK && requestCode == TRADING)
		{
			// Log.d("Hai", "Been here too");
			ResourceWrapper changedResources = (ResourceWrapper) data.getSerializableExtra("Resources");

			for (Resource resource : changedResources.getResourcesArray())
			{
				if (resource != null)
				{
					// Log.d("hoi", resource.getResourceType() + " " + resource.getAmount());
					game.addResourceAmount(resource.getResourceType(), resource.getAmount());
				}
			}
			game.forceUpdate(false);

		}
		else if (resultCode == RESULT_OK && requestCode == UPGRADE_SCREEN_REQUEST_CODE)
		{
			if (game.getSelectedTile() instanceof BuildingTile)
			{
				Building selectedBuilding = ((BuildingTile) game.getSelectedTile()).getBuilding();
				game.upgradeBuilding(selectedBuilding);
				Toast.makeText(getApplicationContext(), "upgraded " + selectedBuilding.getBuildingName() +
					" to level " + selectedBuilding.getBuildingLevel(), Toast.LENGTH_SHORT).show();
				game.substractResourceAmount(ResourceType.SCIENCEPOINTS,
					data.getIntExtra("Upgrading.SciencePointCosts", 0));
				game.forceUpdate(false);
			}
		}
		else if (resultCode == RESULT_OK && requestCode == SELL_SCREEN_REQUEST_CODE)
		{
			if (game.getSelectedTile() instanceof BuildingTile)
			{
				Building selectedBuilding = ((BuildingTile) game.getSelectedTile()).getBuilding();
				selectedBuilding.upgradeBuildingLevel();
				Toast.makeText(getApplicationContext(), "sold " + selectedBuilding.getBuildingName(),
					Toast.LENGTH_SHORT).show();
				game.removeBuilding(selectedBuilding, true, false);
				game.forceUpdate(false);
			}
		}
	}

	public void showBuildingPopup()
	{
		// Log.d("GameScreen", "Starting building screen, observer count: " + game.countObservers());
		Intent newBuildingPopup = new Intent(this, BuildingScreen.class);
		newBuildingPopup.putExtra("GameScreen.Resources", new ResourceWrapper(game.getResourceArray()));
		startActivityForResult(newBuildingPopup, BUILDING_SCREEN_REQUEST_CODE);
	}

	public void showUpgradePopup()
	{
		Intent newUpgradeBuildingPopup = new Intent(this, CustomUpgradePopup.class);
		newUpgradeBuildingPopup.putExtra("GameScreen.Resources", new ResourceWrapper(game.getResourceArray()));
		newUpgradeBuildingPopup.putExtra("GameScreen.Tile", game.getSelectedTile());
		startActivityForResult(newUpgradeBuildingPopup, UPGRADE_SCREEN_REQUEST_CODE);
	}

	public void showSellPopup()
	{
		Intent newSellBuildingPopup = new Intent(this, CustomSellPopup.class);
		newSellBuildingPopup.putExtra("GameScreen.Resources", new ResourceWrapper(game.getResourceArray()));
		newSellBuildingPopup.putExtra("GameScreen.Tile", game.getSelectedTile());
		startActivityForResult(newSellBuildingPopup, SELL_SCREEN_REQUEST_CODE);
	}

	public void showTradePopup()
	{
		boolean hasMarket = false;
		for (Building b : game.getBuildings())
		{
			if (b.getClass() == SpaceMarket.class)
			{
				hasMarket = true;
			}
		}
		if (hasMarket)
		{
			Intent newTradePopup = new Intent(this, MarketScreen.class);

			// resources meegeven.
			newTradePopup.putExtra("MarketScreen.TradeWrapper",
				new ResourceAndPlanetWrapper(game.getResourceAmount(ResourceType.MONEY), game.getTradePlantes()));

			// TRADING = 4;
			startActivityForResult(newTradePopup, TRADING);
		}
		else
		{
			Toast.makeText(this.getApplicationContext(), "You need a space market first",
				Toast.LENGTH_LONG).show();
		}

	}

	public void showachievementScreen()
	{
		Intent newAchievementPopup = new Intent(this, AchievementScreen.class);
		startActivity(newAchievementPopup);
	}

	public void showNewAchievementAlert(Achievement achievement)
	{

		stopTimerFromPausing = true;
		Intent showAchievementPopup = new Intent(this.getApplicationContext(), CustomAchievementPopup.class);
		showAchievementPopup.putExtra("saxion.speelveld.spaceengineer.achievement", achievement);
		startActivityForResult(showAchievementPopup, ACHIEVEMENT_SCREEN_REQUEST_CODE);

	}

	public void showInvalidBuildingSpotToast()
	{
		Toast.makeText(this.getApplicationContext(), "Uh-oh, please select a proper building location",
			Toast.LENGTH_LONG).show();
	}

	public void closeDialog()
	{
		try
		{
			progdialog.dismiss();
			progdialog = null;
		}
		catch (Exception e)
		{
			// nothing
		}
	}

	public void updateDialog(int progress)
	{
		progdialog.setProgress(progress);
	}

	private class SaveCurrentGame extends AsyncTask<Context, Integer, Long>
	{

		@Override
		protected Long doInBackground(Context... params)
		{
			// Log.e("SaveCurrentGame", "Starting!");

			gameDatasource.open();
			// gameDatasource.saveExistingGameDataAndChildren(game, game.getGameId());
			gameDatasource.saveExistingGameDataAndChildren(game, game.getGameId());
			gameDatasource.close();
			updateAsyncTaskRunning = false;

			// Log.e("SaveCurrentGame", "DONE!");
			return null;
		}

		@Override
		protected void onPostExecute(Long result)
		{
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			updateAsyncTaskRunning = false;
		}

		@SuppressLint("NewApi")
		@Override
		protected void onCancelled(Long result)
		{
			// TODO Auto-generated method stub
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
			{
				super.onCancelled(result);
			}
			updateAsyncTaskRunning = false;
		}

		@Override
		protected void onCancelled()
		{
			// TODO Auto-generated method stub
			super.onCancelled();
			updateAsyncTaskRunning = false;
		}

	}

	public void finishActivity()
	{
		this.finish();
	}

	private class SaveNewGameToDB extends AsyncTask<Context, Integer, Long>
	{

		@Override
		protected Long doInBackground(Context... params)
		{
			int progress = 5;
			gameDatasource.open();
			int addedId = gameDatasource.createNewSaveGame(game);
			game.setGameId(addedId);
			gameDatasource.close();

			publishProgress(progress);

			// Log.d("SaveNewGameToDB", "Created game :)");

			// Try saving building types

			try
			{
				buildingTypeDatasource.open();
				buildingTypeDatasource.setInitialBuildingTypes();
			}
			finally
			{
				buildingTypeDatasource.close();
			}

			progress = 10;
			publishProgress(progress);

			try
			{
				buildingDatasource.open();
				buildingDatasource.beginTransactionMode();

				int buildingArrayListSize = game.getBuildings().size();
				for (int i = 0; i < buildingArrayListSize; i++)
				{
					buildingDatasource.putBuilding(addedId, game.getBuildings().get(i), i);

				}
				game.setBuildingsUpdated(false);
				buildingDatasource.setTransactionModeSuccesfull();

			}
			finally
			{
				buildingDatasource.endTransactionMode();
				buildingDatasource.close();
			}

			// Try saving all tiles
			try
			{
				tileDatasource.open();
				tileDatasource.beginTransactionMode();
				for (int x = 0; x < game.getField().length; x++)
				{
					for (int y = 0; y < game.getField()[0].length; y++)
					{
						tileDatasource.PutTile(addedId, game.getField()[x][y], x, y, false);
						game.getField()[x][y].setDirty(false);
					}
					progress += 1;
					publishProgress(progress);
				}
				Game.setTilesUpdated(false);
				tileDatasource.setTransactionModeSuccesfull();
			}
			finally
			{
				tileDatasource.endTransactionMode();
				tileDatasource.close();
			}

			// Log.d("SaveNewGameToDB", "Created tiles :)");

			// Try saving starting resources
			resourceDatasource.open();
			try
			{
				resourceDatasource.beginTransactionMode();
				for (Resource res : game.getResourceArray())
				{
					resourceDatasource.putResourceForGame(addedId, res);
					progress += 1;
					publishProgress(progress);
				}
				resourceDatasource.setTransactionModeSuccesfull();
			}
			finally
			{
				resourceDatasource.endTransactionMode();
				resourceDatasource.close();
			}

			// Try saving all trade planets/deals
			try
			{
				tradePlanetDatasource.open();
				tradePlanetDatasource.putTradePlanetsForGame(addedId, game.getTradePlantes());

			}
			finally
			{
				tradePlanetDatasource.close();
			}

			progress += game.getTradePlantes().length;
			publishProgress(progress);

			return null;
		}

		@Override
		protected void onPostExecute(Long result)
		{
			closeDialog();
			afterLoad();
		}

		@Override
		protected void onPreExecute()
		{
		}

		@Override
		protected void onProgressUpdate(Integer... values)
		{
			updateDialog(values[0]);
		}
	}

	private class LoadSaveGameFromDB extends AsyncTask<Integer, Integer, Long>
	{

		@Override
		protected Long doInBackground(Integer... args)
		{
			int maxTimeOutInSeconds = 5;
			int startSec = Calendar.getInstance().get(Calendar.SECOND);
			while (AsyncTaskManager.getAsyncTaskStatus() != Status.FINISHED)
			{
				try
				{
					Thread.sleep(1000);
					Log.e("LoadSaveGame", "not finished..?");
				}
				catch (InterruptedException e)
				{

				}
				int currentSec = Calendar.getInstance().get(Calendar.SECOND);
				if (currentSec > startSec + maxTimeOutInSeconds)
				{
					// return null;
				}
			}

			gameDatasource.open();
			game = gameDatasource.loadExistingGame(args[0]);
			gameDatasource.close();
			return null;
		}

		@Override
		protected void onPostExecute(Long result)
		{

			closeDialog();
			afterLoad();
			loadAsyncTaskRunning = false;
		}

		@SuppressLint("NewApi")
		protected void onCancelled(Long result)
		{
			// TODO Auto-generated method stub
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
			{
				super.onCancelled(result);
			}
			loadAsyncTaskRunning = false;
		}

		@Override
		protected void onProgressUpdate(Integer... values)
		{
			updateDialog(values[0]);
		}

	}

	@Override
	protected void onPause()
	{
		// Log.w("GameScreen.onPause", "Game is being paused....");
		super.onPause();
		if (stopTimerFromPausing == false)
		{
			TimedEvents.StopTimer();
		}
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		TimedEvents.RestartTimer(game);
	}

	@Override
	protected void onDestroy()
	{
		// Log.w("GameScreen.onDestroy", "Game is being paused....");
		super.onDestroy();
	}

	@Override
	public void onBackPressed()
	{

		if (game.getQueuedBuilding() != null || game.isBuildInfrastructure() == true)
		{
			game.setQueuedBuilding(null);
			game.setBuildInfrastructure(false);
		}
		else
		{
			TimedEvents.StopTimer();
			super.onBackPressed();
		}
	}

}
